new Vue({
    el: '#app',
    data: {
        products: [],
        activeCategory: 0,
        categories: [],
        userAvatarUrl: 'https://randomuser.me/api/portraits/men/32.jpg',
        username: '',
        loading: false,
        searchKeyword: '',
        menuOpen: false,
        //轮播图数据
        carouselItems: [],
        carouselCurrentIndex: 0,
        carouselInterval: null,
        showCarouselAndTitle: true, // 新增属性，控制轮播图和商品标题的显示
        newUserCoupon: null,
        showCouponModal: false, // 控制优惠券弹窗显示
        isNewUser: false, // 新增：标记是否为新用户
    },

    created() {
        // 检查token和userId
        if (!localStorage.getItem('token') || !localStorage.getItem('userId')) {
            alert('未检测到登录信息，请重新登录！');
            window.location.href = '/login.html';
            return;
        }
        // 主页面数据加载
        this.findAllClassfiy();
        this.fetchUserInfo();
        this.fetchCarouselData();
        // 新用户自动弹窗逻辑
        this.checkNewUser();
    },
    methods: {
        toggleMenu() {
            this.menuOpen = !this.menuOpen;
        },

        // 获取所有分类
        findAllClassfiy() {
            $.ajax({
                url: 'http://localhost:8080/index/findAllClassify',
                type: 'GET',
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                success: response => {
                    if (response.code === 200) {
                        this.categories = response.data;
                        // 默认选中第一个分类
                        if (this.categories.length > 0) {
                            this.activeCategory = this.categories[0].id;
                            this.fetchProducts(this.activeCategory);
                        }
                    } else {
                        console.error('加载分类失败：' + response.message);
                    }
                },
                error: response => {
                    console.error('加载分类失败：' + response.message);
                }
            })
        },
        // 分类切换
        filterCategory(categoryId) {
            this.activeCategory = categoryId;
            this.fetchProducts(categoryId);
        },

        // 获取商品列表
        fetchProducts(categoryId = 0) {
            // 如果没有搜索关键字，确保显示轮播图和标题
            if (!this.searchKeyword.trim()) {
                this.showCarouselAndTitle = true;
            }
            $.ajax({
                url: 'http://localhost:8080/index/findAll',
                type: 'GET',
                data: { categoryId: categoryId },
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                dataType: 'json',
                success: (response) => {
                    console.log(response);
                    if (response.code === 200) {
                        this.products = response.data;
                        this.products.forEach(product => {
                            // 处理商品图片路径
                            if (product.commodityPicture && product.commodityPicture.length > 0) {
                                product.image = 'http://localhost:8080' + product.commodityPicture[0].commodityImageUrl;
                            } else {
                                product.image = '';
                            }
                        });
                    } else {
                        this.products = [];
                        console.error('加载商品失败：' + response.message);
                    }
                },
                error: () => {
                    this.products = [];
                    console.error('加载商品失败，请稍后重试');
                }
            });
        },

        // 搜索商品
        searchProducts() {
            if (!this.searchKeyword.trim()) {
                this.fetchProducts(this.activeCategory); // 清空搜索时，重新加载当前分类的商品
                this.showCarouselAndTitle = true; // 清空搜索时显示轮播图和标题和分类按钮
                return;
            }
            this.showCarouselAndTitle = false; // 执行搜索时隐藏轮播图和标题和分类按钮

            $.ajax({
                url: 'http://localhost:8080/commodity/search',
                method: 'GET',
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                data: {
                    keyword: this.searchKeyword,
                    categoryId: this.activeCategory
                },
                success: (response) => {
                    if (response.code === 200) {
                        this.products = response.data;
                        this.products.forEach(product => {
                            // 处理商品图片路径
                            if (product.commodityPicture && product.commodityPicture.length > 0) {
                                product.image = 'http://localhost:8080' + product.commodityPicture[0].commodityImageUrl;
                            } else {
                                product.image = '';
                            }
                        });
                    } else {
                        this.products = [];
                        console.error('搜索失败：' + response.message);
                    }
                },
                error: () => {
                    this.products = [];
                    console.error('搜索请求失败，请稍后重试');
                }
            });
        },
        // 获取用户个人信息
        fetchUserInfo() {
            const token = localStorage.getItem('token') || ''; // 从本地存储获取token
            if (!token) {
                console.warn('未找到用户token，无法加载用户信息。');
                this.userAvatarUrl = '/photo/Profile picture/微信图片_20240927140746.jpg';
                this.username = '请登录';
                return;
            }

            $.ajax({
                url: 'http://localhost:8080/user/findUserById',
                type: 'Post',
                dataType: 'json',
                headers: {
                    'token': token
                },
                data: {
                    userId: localStorage.getItem('userId') || ''
                },
                success: (response) => {
                    if (response.code === 200) {
                        this.username = response.data.userName;
                        this.userAvatarUrl = 'http://localhost:8080' + response.data.avatar;
                        console.log(this.username);
                        console.log(this.userAvatarUrl);

                        // 检查是否为新用户
                        // this.checkNewUser();
                    }
                },
                error: function (xhr, status, error) {
                    console.error('加载用户信息失败:', error, xhr.responseText);
                    if (xhr.status === 401) {
                        // token过期或无效
                        logout(); // 调用 logout 函数清除存储并跳转
                    } else {
                        alert('加载用户信息失败，请稍后重试');
                    }
                }
            });
        },
        // 新增：检查是否为新用户
        checkNewUser() {
            $.ajax({
                url: 'http://localhost:8080/user/checkNewUser',
                type: 'GET',
                headers: { 'token': localStorage.getItem('token') || '' },
                data: { userId: localStorage.getItem('userId') || '' },
                success: (response) => {
                    if (response.code === 200 && response.data) {
                        this.isNewUser = true;
                        // 直接获取券模板信息并弹窗
                        this.getNewUserCouponInfo();
                    }
                },
                error: (error) => {
                    console.error('检查新用户状态失败:', error);
                }
            });
        },
        // 获取新人券模板信息并弹窗
        getNewUserCouponInfo() {
            $.ajax({
                url: 'http://localhost:8080/coupon/getNewUserCouponInfo',
                type: 'GET',
                headers: { 'token': localStorage.getItem('token') || '' },
                success: (res) => {
                    if (res.code === 200 && res.data) {
                        this.newUserCoupon = res.data;
                        this.showCouponModal = true;
                        console.log('获取新人券模板信息成功', res.data);
                    }
                },
                error: (err) => {
                    console.error('获取新人券模板信息失败:', err);
                }
            });
        },
        // 领取新人券
        sendNewUserCoupon() {
            $.ajax({
                url: 'http://localhost:8080/coupon/sendNewUserCoupon',
                type: 'POST',
                headers: { 'token': localStorage.getItem('token') || '' },
                data: { userId: localStorage.getItem('userId') || '' },
                success: (response) => {
                    if (response.code === 200) {
                        alert('领取成功！，请在我的优惠券查看');
                        this.showCouponModal = false;
                        this.isNewUser = false;
                    } else {
                        console.log('领取失败：' + response.message);
                    }
                },
                error: () => {
                    alert('领取失败，请稍后重试');
                }
            });
        },
        //点击退出跳转到登录页面
        logout() {
            localStorage.removeItem('token'); // 删除token
            localStorage.removeItem('userId'); // 删除userId
            // 更新UI显示
            this.username = '请登录';
            this.userAvatarUrl = '/photo/Profile picture/微信图片_20241015154525.jpg';
            // 刷新页面数据
            this.fetchProducts(this.activeCategory);
        },
        // 处理用户点击事件
        handleUserClick() {
            if (this.username === '请登录') {
                window.location.href = '/login.html';
            }
        },
        // 修改：关闭优惠券弹窗
        closeCouponModal() {
            this.showCouponModal = false;
            this.isNewUser = false;
            localStorage.setItem('showCouponPrompt', 'false');
        },
        //获取推荐商品数据
        fetchCarouselData() {
            $.ajax({
                url: 'http://localhost:8080/index/findRecommend',
                type: 'GET',
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                data: {
                    userId: localStorage.getItem('userId') || ''
                },
                success: (response) => {
                    if (response.code === 200) {
                        console.log(response.data);
                        
                        this.carouselItems = response.data.map(item => {
                            // 确保有图片URL
                            let imageUrl = '/photo/default-carousel.jpg'; // 默认图片
                            if (item.commodityPicture && item.commodityPicture.length > 0) {
                                const match =item.commodityPicture[0].commodityImageUrl;
                                imageUrl = 'http://localhost:8080'+match;
                            }

                            return {
                                imageUrl: imageUrl,
                                title: item.commodityName,
                                description: item.commodityDescribe || '精选推荐商品'
                            };
                        });

                        // 如果获取到数据，启动轮播
                        if (this.carouselItems.length > 0) {
                            this.startAutoPlay();
                        }
                    } else {
                        console.error('加载轮播图数据失败：' + response.message);
                        // 设置默认轮播图数据
                        this.setDefaultCarousel();
                    }

                },
                error: (xhr, status, error) => {
                    console.error('加载轮播图数据失败：' + error);
                }

            })
        },
        currentSlideIndex() {
            return this.carouselCurrentIndex;
        },

        // 自动播放
        startAutoPlay() {
            if (this.carouselItems.length <= 1) return;

            this.stopAutoPlay(); // 先清除旧定时器
            this.carouselInterval = setInterval(() => {
                this.nextSlide();
            }, 3000);
        },

        stopAutoPlay() {
            if (this.carouselInterval) {
                clearInterval(this.carouselInterval);
                this.carouselInterval = null;
            }
        },

        nextSlide() {
            this.carouselCurrentIndex = (this.carouselCurrentIndex + 1) % this.carouselItems.length;
            this.updateSlide();
        },

        prevSlide() {
            this.carouselCurrentIndex = (this.carouselCurrentIndex - 1 + this.carouselItems.length) % this.carouselItems.length;
            this.updateSlide();
        },

        goToSlide(index) {
            this.carouselCurrentIndex = index;
            this.updateSlide();
        },

        updateSlide() {
            const wrapper = document.querySelector('.carousel-wrapper');
            if (wrapper) {
                wrapper.style.transform = `translateX(-${this.carouselCurrentIndex * 100}%)`;
            }
        },
        // 预览券有效期（当前时间~7天后）
        getPreviewCouponPeriod(days = 7) {
            const now = new Date();
            const end = new Date(now.getTime() + days * 24 * 60 * 60 * 1000);
            const format = d => d.getFullYear() + '-' +
                String(d.getMonth() + 1).padStart(2, '0') + '-' +
                String(d.getDate()).padStart(2, '0') + ' ' +
                String(d.getHours()).padStart(2, '0') + ':' +
                String(d.getMinutes()).padStart(2, '0') + ':' +
                String(d.getSeconds()).padStart(2, '0');
            return `有效期：${format(now)} ~ ${format(end)}`;
        },
        // 计算券剩余天数
        getRemainingDays(endTime) {
            if (!endTime) return '';
            const end = new Date(endTime.replace(/-/g, '/'));
            const now = new Date();
            const diff = end - now;
            if (diff <= 0) return '已过期';
            const days = Math.ceil(diff / (1000 * 60 * 60 * 24));
            // return `剩余${days}天`;
        },
        formatDate(dateString) {
            if (!dateString) return '无限制';
            const date = new Date(dateString);
            return date.toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
        },
        getStatusClass(status) {
            return {
                0: 'status-available',
                1: 'status-used',
                2: 'status-expired'
            }[status] || '';
        },
        getStatusText(status) {
            return {
                0: '未使用',
                1: '已使用',
                2: '已过期'
            }[status] || '未知状态';
        },

    },
    watch: {
        searchKeyword(newVal) {
            // 当搜索关键词被清空时，显示轮播图和标题，并重新加载当前分类的商品
            if (!newVal.trim()) {
                this.showCarouselAndTitle = true;
                this.fetchProducts(this.activeCategory);
            }
        }
    },
    mounted() {
        this.startAutoPlay(); // 启动轮播图自动播放
        // 监听鼠标悬停事件
        const container = document.querySelector('.carousel-container');
        if (container) {
            container.addEventListener('mouseenter', this.stopAutoPlay);
            container.addEventListener('mouseleave', this.startAutoPlay);
        }
    }
});
// $(document).ready(function () {
//     const carousel = {
//         currentIndex: 0,
//         timer: null,
//         slidesCount: $('.carousel-slide').length,

//         init() {
//             this.bindEvents();
//             this.startAutoPlay();
//             this.fetchCarouselData();
//         },

//         bindEvents() {
//             $('.carousel-btn.prev').on('click', () => this.prevSlide());
//             $('.carousel-btn.next').on('click', () => this.nextSlide());

//             $('.dot').each((index, dot) => {
//                 $(dot).on('click', () => this.goToSlide(index));
//             });

//             $('.carousel-container').hover(
//                 () => this.stopAutoPlay(),
//                 () => this.startAutoPlay()
//             );
//         },

//         startAutoPlay() {
//             this.stopAutoPlay();
//             this.timer = setInterval(() => this.nextSlide(), 3000);
//         },

//         stopAutoPlay() {
//             if (this.timer) {
//                 clearInterval(this.timer);
//                 this.timer = null;
//             }
//         },

//         updateSlide() {
//             $('.carousel-wrapper').css('transform', `translateX(-${this.currentIndex * 100}%)`);
//             $('.dot').removeClass('active').eq(this.currentIndex).addClass('active');
//         },

//         nextSlide() {
//             this.currentIndex = (this.currentIndex + 1) % this.slidesCount;
//             this.updateSlide();
//         },

//         prevSlide() {
//             this.currentIndex = (this.currentIndex - 1 + this.slidesCount) % this.slidesCount;
//             this.updateSlide();
//         },

//         goToSlide(index) {
//             this.currentIndex = index;
//             this.updateSlide();
//         },

//     };

//     // 初始化轮播图
//     carousel.init();
// });